#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
增强版提示词工程演示脚本
展示个性化、上下文感知和智能优化功能
"""

import sys
import os
import asyncio

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

from src.research_core.prompt_eng_state import PromptEngineeringState
from src.research_core.enhanced_prompt_eng_workflow import (
    create_enhanced_prompt_engineering_workflow,
    execute_enhanced_prompt_engineering_workflow,
    create_personalized_prompt_engineering_workflow
)


async def demo_enhanced_prompt_engineering():
    """演示增强版提示词工程功能"""
    print("=== 增强版提示词工程功能演示 ===\n")
    
    # 定义需求
    requirement = """
    我需要一个能够帮助用户进行数据分析的AI助手提示词。这个助手应该能够：
    1. 理解用户的具体数据分析任务（描述性统计、假设检验、预测建模等）
    2. 根据数据特征推荐合适的分析方法
    3. 提供分析代码和解释
    4. 解释分析结果的含义
    5. 给出数据可视化建议
    """
    
    # 初始化状态
    initial_state: PromptEngineeringState = {
        "requirement": requirement,
        "requirement_analysis": "",
        "current_prompt": None,
        "human_feedback": None,
        "feedback_history": [],
        "optimization_goal": "提高提示词在数据分析任务中的指导性和完整性",
        "prompt_evaluation": None,
        "final_prompt": None,
        "design_reasoning": None,
        "iteration_count": 0,
        "workflow_complete": False,
        "human_intervened": False,
        "current_stage": "start",
        "quality_score": 0.0,
        "execution_time": {},
        "context_info": {},
        "metadata": {},
        "ab_test_results": None,
        "performance_metrics": [],
        "user_feedbacks": [],
        "optimization_history": [],
        "prompt_versions": {},
        "test_results": None,
        "user_preferences": {},
        "domain_context": None,
        "interaction_history": [],
        "personalization_settings": {},
        "template_recommendations": [],
        "quality_evaluation_details": None,
        "ab_test_variants": [],
        "quality_history": [],
        "decision_log": [],
        "workflow_metrics": {}
    }
    
    # 执行工作流
    print("正在执行增强版提示词工程工作流...")
    result = execute_enhanced_prompt_engineering_workflow(initial_state)
    
    if result["success"]:
        final_state = result["final_state"]
        print("✅ 工作流执行成功")
        print(f"最终质量评分: {final_state.get('quality_score', 0.0)}")
        print("\n最终生成的提示词:")
        print(final_state.get("final_prompt", "无提示词生成"))
        print("\n设计说明:")
        print(final_state.get("design_reasoning", "无设计说明"))
        
        # 显示执行时间统计
        execution_time = final_state.get("execution_time", {})
        if execution_time:
            print("\n执行时间统计:")
            for stage, duration in execution_time.items():
                print(f"- {stage}: {duration:.2f}秒")
    else:
        print(f"❌ 工作流执行失败: {result['error']}")


async def demo_personalized_prompt_engineering():
    """演示个性化提示词工程功能"""
    print("\n=== 个性化提示词工程功能演示 ===\n")
    
    # 定义需求
    requirement = """
    我需要一个能够帮助初学者学习Python编程的AI助手提示词。这个助手应该能够：
    1. 用简单易懂的语言解释编程概念
    2. 提供循序渐进的学习路径
    3. 给出大量示例代码
    4. 耐心回答学习者的问题
    5. 鼓励学习者持续学习
    """
    
    # 模拟用户交互历史
    interaction_history = [
        {
            "timestamp": "2023-01-01T10:00:00",
            "content": "希望提示词更简单易懂，不要太技术化",
            "type": "feedback"
        },
        {
            "timestamp": "2023-01-02T15:00:00",
            "content": "喜欢结构化的学习内容，有清晰的步骤",
            "type": "feedback"
        }
    ]
    
    # 初始化状态
    initial_state: PromptEngineeringState = {
        "requirement": requirement,
        "requirement_analysis": "",
        "current_prompt": None,
        "human_feedback": None,
        "feedback_history": [],
        "optimization_goal": "提高提示词对初学者的友好性和教学效果",
        "prompt_evaluation": None,
        "final_prompt": None,
        "design_reasoning": None,
        "iteration_count": 0,
        "workflow_complete": False,
        "human_intervened": False,
        "current_stage": "start",
        "quality_score": 0.0,
        "execution_time": {},
        "context_info": {},
        "metadata": {},
        "ab_test_results": None,
        "performance_metrics": [],
        "user_feedbacks": [],
        "optimization_history": [],
        "prompt_versions": {},
        "test_results": None,
        "user_preferences": {},
        "domain_context": None,
        "interaction_history": interaction_history,
        "personalization_settings": {},
        "template_recommendations": [],
        "quality_evaluation_details": None,
        "ab_test_variants": [],
        "quality_history": [],
        "decision_log": [],
        "workflow_metrics": {}
    }
    
    # 创建并执行个性化工作流
    print("正在创建个性化提示词工程工作流...")
    try:
        workflow = create_personalized_prompt_engineering_workflow()
        app = workflow.compile()
        
        print("正在执行个性化提示词工程工作流...")
        final_state = app.invoke(initial_state)
        
        print("✅ 个性化工作流执行成功")
        print(f"最终质量评分: {final_state.get('quality_score', 0.0)}")
        print("\n最终生成的提示词:")
        print(final_state.get("final_prompt", "无提示词生成"))
        print("\n设计说明:")
        print(final_state.get("design_reasoning", "无设计说明"))
        
        # 显示用户偏好
        user_preferences = final_state.get("user_preferences", {})
        if user_preferences:
            print("\n检测到的用户偏好:")
            for key, value in user_preferences.items():
                print(f"- {key}: {value}")
                
    except Exception as e:
        print(f"❌ 个性化工作流执行失败: {e}")


async def demo_with_human_feedback():
    """演示带有人工反馈的增强版提示词工程"""
    print("\n=== 带有人工反馈的增强版提示词工程演示 ===\n")
    
    # 定义需求
    requirement = """
    我需要一个能够帮助用户进行机器学习模型选择的AI助手提示词。这个助手应该能够：
    1. 理解用户的具体机器学习任务（分类、回归、聚类等）
    2. 根据数据特征推荐合适的算法
    3. 提供模型训练和评估的指导
    4. 解释模型结果的含义
    5. 给出模型优化建议
    """
    
    # 初始化状态（包含人工反馈）
    initial_state: PromptEngineeringState = {
        "requirement": requirement,
        "requirement_analysis": "",
        "current_prompt": None,
        "human_feedback": "请更加强调模型选择的可解释性和业务适用性，而不仅仅是准确性",
        "feedback_history": [],
        "optimization_goal": "提高提示词在机器学习任务中的实用性",
        "prompt_evaluation": None,
        "final_prompt": None,
        "design_reasoning": None,
        "iteration_count": 0,
        "workflow_complete": False,
        "human_intervened": True,  # 标记有人工介入
        "current_stage": "start",
        "quality_score": 0.0,
        "execution_time": {},
        "context_info": {},
        "metadata": {},
        "ab_test_results": None,
        "performance_metrics": [],
        "user_feedbacks": [],
        "optimization_history": [],
        "prompt_versions": {},
        "test_results": None,
        "user_preferences": {},
        "domain_context": None,
        "interaction_history": [],
        "personalization_settings": {},
        "template_recommendations": [],
        "quality_evaluation_details": None,
        "ab_test_variants": [],
        "quality_history": [],
        "decision_log": [],
        "workflow_metrics": {}
    }
    
    # 执行工作流
    print("正在执行带有人工反馈的增强版提示词工程工作流...")
    result = execute_enhanced_prompt_engineering_workflow(initial_state)
    
    if result["success"]:
        final_state = result["final_state"]
        print("✅ 工作流执行成功")
        print(f"最终质量评分: {final_state.get('quality_score', 0.0)}")
        print("\n最终生成的提示词:")
        print(final_state.get("final_prompt", "无提示词生成"))
        print("\n设计说明:")
        print(final_state.get("design_reasoning", "无设计说明"))
        
        print("\n反馈历史:")
        for feedback in final_state.get("feedback_history", []):
            print(f"- {feedback['type']}反馈 ({feedback['timestamp']}): {feedback['content']}")
    else:
        print(f"❌ 工作流执行失败: {result['error']}")


async def main():
    """主函数"""
    await demo_enhanced_prompt_engineering()
    print("\n" + "="*70 + "\n")
    await demo_personalized_prompt_engineering()
    print("\n" + "="*70 + "\n")
    await demo_with_human_feedback()


if __name__ == "__main__":
    asyncio.run(main())